<?php

namespace Framework;

use App\Http\Handler\MainHandler;
use Psr\Http\Message\ServerRequestInterface;

class MiddlewareRunner
{
    protected static $mainHandler = MainHandler::class;

    protected static $middlewareList = [];

    public static function setMainHandler($mainHandler)
    {
        self::$mainHandler = $mainHandler;
    }

    public static function runWithMiddleware(ServerRequestInterface $request, array $middlewareList = [], $mainHandler = MainHandler::class)
    {
        self::$middlewareList = $middlewareList;
        self::$mainHandler = $mainHandler;

        return self::next($request);
    }

    public static function next(ServerRequestInterface $request)
    {
        if (empty(self::$middlewareList)) {
            return call_user_func([self::$mainHandler, 'handle'], $request);
        }

        $middlewareName = array_shift(self::$middlewareList);
        $middleware = new $middlewareName;
        return call_user_func([$middleware, 'process'], $request, $middleware->getHandler());
    }
}
